﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Net.Browser;
using System.Collections.Generic;

namespace SkyDriveConnector
{
    public class SkyDriveModel : IConnectorOperations
    {

        public string AuthToken { get; set; }

        public event EventHandler<EventArgs> SkyDriveItemsLoadingComplete;

        public event EventHandler<EventArgs> SharePointItemsLoadingComplete;

        public event EventHandler<EventArgs> AddSkyDriveFolderComplete;

        public event EventHandler<EventArgs> AddSharePointFolderComplete;

        public event EventHandler<EventArgs> AddSkyDriveItemComplete;

        public event EventHandler<EventArgs> AddSharePointItemComplete;

        public event EventHandler<EventArgs> DeleteSkyDriveItemComplete;

        public event EventHandler<EventArgs> DeleteSharePointItemComplete;

        public event EventHandler<ItemLoadingErrorEventArgs> SkyDriveItemLoadingOnError;

        public event EventHandler<ItemLoadingErrorEventArgs> SharePointItemLoadingOnError;
        //public event EventHandler<EventArgs> ItemsLoadingComplete;

        //public event EventHandler<EventArgs> AddNewItemComplete;

        //public event EventHandler<EventArgs> DeleteItemComplete;

        //public event EventHandler<ItemLoadingErrorEventArgs> ItemLoadingOnError;

        private static string _skydriveUrl = "https://apis.live.net/v5.0/";
        private string _skydriveRootPath = "me/skydrive/files";
        private Uri _skydriveUri;


        private Uri GetSkyDrivePath(string path)
        {
            if (path == "")
                path = _skydriveUrl + _skydriveRootPath;

            //path = "https://apis.live.net/v5.0/folder.77ecf790debcf246.77ECF790DEBCF246!109/files/";

            return new Uri(string.Format(path + "?access_token={0}", GetToken()));
        }

        private string GetToken()
        {
            return AuthToken;

        }

        public void GetItems(string path, int CorrelationId)
        {
            HttpWebRequest webreq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(GetSkyDrivePath(path));
            webreq.BeginGetResponse(new AsyncCallback(result =>
            {
                try
                {
                    WebResponse webresponse = webreq.EndGetResponse(result);
                    StreamReader reader = new StreamReader(webresponse.GetResponseStream());
                    var objskd = JSONHelper.Deserialize<SkyDriveItems>(reader.ReadToEnd());

                    //if (objskd.data.Length == 0)
                    //{
                    //    Array.Resize(ref objskd.data, 1);
                    //    var empty = new SkyDriveObject();
                    //    empty.name = "Empty";
                    //    empty.type = "file";
                    //    objskd.data[0] = empty;

                    //}
                    ItemLoadingCompleteEventArgs<SkyDriveObject> skydriveLoadCompleteEventArgs = new ItemLoadingCompleteEventArgs<SkyDriveObject>(objskd.data, CorrelationId,"SkyDrive GetItems Complete","");
                    SkyDriveItemsLoadingComplete(this, skydriveLoadCompleteEventArgs);

                }
                catch (WebException ex)
                {
                    ItemLoadingErrorEventArgs skydriveErrorsEventArgs = new ItemLoadingErrorEventArgs(ex.Message);
                    SkyDriveItemLoadingOnError(this, skydriveErrorsEventArgs);

                }
                catch (Exception ex)
                {
                    ItemLoadingErrorEventArgs skydriveErrorsEventArgs = new ItemLoadingErrorEventArgs(ex.Message);
                    SkyDriveItemLoadingOnError(this, skydriveErrorsEventArgs);

                }
            }), webreq);
        }

        public void GetSingleItem(string ItemId, int CorrelationId)
        {
            throw new NotImplementedException();
        }

        public void AddNewItem()
        {
            throw new NotImplementedException();
        }

        public void AddNewItem(string path, FileStream filestream, string filename, int CorrelationId)
        {
            Uri skydriveuri = new Uri(string.Format("https://apis.live.net/v5.0/{2}/files/{1}?access_token={0}", GetToken(), filename,path));
            HttpWebRequest rq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(skydriveuri);

            rq.Method = "PUT";
            rq.BeginGetRequestStream(new AsyncCallback(result => this.uploadfile(result, filestream, CorrelationId, path)), rq);
        }

        private void uploadfile(IAsyncResult result, FileStream file, int CorrelationId, string parentid)
        {
            HttpWebRequest webreq = (HttpWebRequest)result.AsyncState;

            using (Stream stream = webreq.EndGetRequestStream(result))
            {
                int read = 0;
                byte[] buffer = new byte[1024];
                while ((read = file.Read(buffer, 0, buffer.Length)) > 0)
                    stream.Write(buffer, 0, read);

            }
            GetResponse(result, webreq, AddSkyDriveItemComplete, CorrelationId,"SkyDrive Upload File Complete","",parentid);

        }

        private void GetResponse(IAsyncResult result, HttpWebRequest webreq, EventHandler<EventArgs> CompleteAction, int CorrelationId, string Message, string DeleteItemId, string parentid)
        {
            webreq.BeginGetResponse(r =>
            {
                WebResponse webresponse = webreq.EndGetResponse(r);
                StreamReader reader = new StreamReader(webresponse.GetResponseStream());
                var objskd = JSONHelper.Deserialize<SkyDriveResponse>(reader.ReadToEnd());
                if (objskd != null)
                {
                    objskd.filename = objskd.source.Split(new string[] { ":Binary, Default/", ":Binary,Default/" }, StringSplitOptions.None)[1];
                    objskd.parentid = parentid;
                }
                List<SkyDriveResponse> response = new List<SkyDriveResponse>();
                response.Add(objskd);
                ItemLoadingCompleteEventArgs<SkyDriveResponse> CompleteEventArgs = new ItemLoadingCompleteEventArgs<SkyDriveResponse>(response, CorrelationId, (objskd == null) ? Message : JSONHelper.Serialize<SkyDriveResponse>(objskd), DeleteItemId);
                CompleteAction(this, CompleteEventArgs);

            }, webreq);
        }


        public void DeleteItem(string ItemId, int CorrelationId)
        {
            Uri skydriveuri = new Uri(string.Format("https://apis.live.net/v5.0/{1}?access_token={0}", GetToken(),ItemId));
            HttpWebRequest rq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(skydriveuri);

            rq.Method = "DELETE";
            rq.BeginGetRequestStream(new AsyncCallback(result => this.GetResponse(result, rq, DeleteSkyDriveItemComplete, CorrelationId,"SkyDrive DeleteFile Complete",ItemId,"")), rq);

            
        }


        public void CreateFolder(string path, string foldername, string description, int CorrelationId, string skydriveObjectId)
        {
            Uri skydriveuri = new Uri(string.Format("https://apis.live.net/v5.0/{1}/?access_token={0}", GetToken(), path));
            HttpWebRequest request =(HttpWebRequest) WebRequest.Create(skydriveuri);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.BeginGetRequestStream(new AsyncCallback(result =>
                {
                    string uploaddata = string.Format(@"{{""name"": ""{0}"",""description"": ""{1}""}}", foldername, description);
                    Stream stream = request.EndGetRequestStream(result);
                    StreamWriter writer = new StreamWriter(stream);
                    writer.WriteLine(uploaddata);
                    writer.Flush();
                    writer.Close();
                    request.BeginGetResponse(new AsyncCallback(responseResult =>
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(responseResult);
                            Stream responseStream = response.GetResponseStream();
                            StreamReader reader = new StreamReader(responseStream);
                            var objskd = JSONHelper.Deserialize<SkyDriveResponse>(reader.ReadToEnd());
                            List<SkyDriveResponse> skydriveResponse = new List<SkyDriveResponse>();
                            skydriveResponse.Add(objskd);
                            ItemLoadingCompleteEventArgs<SkyDriveResponse> CreateNewFolderComplete = new ItemLoadingCompleteEventArgs<SkyDriveResponse>(skydriveResponse, CorrelationId, JSONHelper.Serialize<SkyDriveResponse>(objskd), objskd.id);
                            AddSkyDriveFolderComplete(this, CreateNewFolderComplete);

                        }), request);

                }), request);


        }




        public void AddNewItem(string path, SkyDriveObject skydriveObject, int CorrelationId)
        {
            throw new NotImplementedException();
        }


        
    }
}
